<template>
	<view class="Shell">
		<private_tip :privateShow="privateb"></private_tip>
		<web-view :src="url"></web-view>
	</view>
</template>

<script>
	var _this,returnUrl = '';
	const app = getApp();
	export default {
		data() {
			return {
				// 辅助数据
				url: '',
				privateb: false,
				platForm: app.globalData.platForm,
				_keyStr:'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
			}
		},
		onLoad(options) {
			_this = this;
			if (app.globalData.wxprivate == -1) {
				app.watchG('wxprivate', function(value) {
					_this.wxprivate=value;
					if (value) { //弹出弹窗
						_this.privateb = true;
					} else {
						_this.onload(options);
					}
				})
			} else {
				if (app.globalData.wxprivate) { //弹出弹窗
					_this.privateb = true;
				} else {
					_this.onload(options);
				}
			}
		},
		onShareAppMessage(res) {
			let config = app.globalData.appConfig;
			return {
				title: config.share.title,
				desc: config.share.description,
				path: '/pages/index/index',
				imageUrl: app.globalData.masterDomain + '/include/json.php?action=getSystemLogo'
			};
		},
		// 分享到朋友圈
		onShareTimeline() {
			return {
				title: config.share.title,
				imageUrl: app.globalData.masterDomain + '/include/json.php?action=getSystemLogo'
			};
		},
		methods: {
			onload(options) {
				//获取options的订单Id
				returnUrl = options.returnUrl ? decodeURIComponent(options.returnUrl) : '';
				if (_this.platForm == 'mp-toutiao') { //抖音支付
					uni.setNavigationBarTitle({
						title: '抖音支付'
					});
					let order_id = decodeURIComponent(options.order_id);
					let order_token = decodeURIComponent(options.order_token);
					//调起支付
					uni.pay({
						//相关支付参数
						orderInfo: {
							order_id: order_id,
							order_token: order_token,
						},
						service: 5,
						//小程序支付成功的回调通知
						'success': function(res) {
							if (res.code == 0) {
								uni.showToast({
									title: '支付成功！',
									icon: 'success',
									duration: 2000
								})
								_this.url = returnUrl
							} else {
								let info = '';
								switch (res.code) {
									case 1:
										info = '支付超时';
									case 2:
										info = '支付失败';
									case 3:
										info = '支付关闭';
									case 4:
										info = '取消支付';
									case 9:
										info = '订单状态未知';
								}
								uni.showToast({
									title: info,
									icon: 'none',
									duration: 2000
								})
								//后退
								app.backFn('/pages/index/index');
							}
						},
						//小程序支付失败的回调通知
						'fail': function(res) {
							uni.showToast({
								title: '支付失败！',
								icon: 'none',
								duration: 2000
							})
							_this.url = returnUrl
						}
					})
				} else if (_this.platForm == 'mp-weixin') { //微信支付
					_this.checkWxOpenid(options)
					
				}
			},


			// 微信支付判断是否有openid
			checkWxOpenid(options){
				if(options.openid){ 
					// 获取到openid 直接支付
					_this.weixinPay(options)
				}else{
					// 未获取到openid
					_this.getWxCode(options)
				}
			},

			// 没有获取openid 通过uni.login获取code 向后台请求openid
			getWxCode(options){
				uni.showLoading({title:'加载中...'})
				uni.login({
					success:function(res){
						if(res.code){
							options['wxmini_code'] = res.code
							_this.reGetOrder(options)
						}
					},
					complete(){
						uni.hideLoading()
					}
				})
			},

			// 重新请求下单
			async reGetOrder(options){
				let param = options.param;
				param = param ? _this.decode(param) :'';
				uni.showLoading({title:'请稍后...'})
				let url = `/include/ajax.php?${param}&wxmini_code=${options.wxmini_code}`
				let urlData = app.encodeUrl(url);    
                let result = await _this.$ajax.post({
					url: urlData, //请求地址
				});
                let data = result.data;
                if(data.state == 100){
                    // 支付
					returnUrl = data.info.orderurl
					_this.weixinPay(data.info)
                }
			},


			// 微信去支付
			weixinPay(options){
				uni.setNavigationBarTitle({
						title: '微信支付'
					});
					//调起支付
					uni.requestPayment({
						//相关支付参数
						timeStamp: options.timestamp || options.timeStamp,
						nonceStr: options.nonceStr,
						package: 'prepay_id=' + options.prepay_id,
						signType: options.signType,
						paySign: decodeURIComponent(options.paySign),
						//小程序微信支付成功的回调通知
						success: function(res) {
							uni.showToast({
								title: '支付成功！',
								icon: 'success',
								duration: 2000,
							});
							setTimeout(res => {
								let url='';
								if(returnUrl.includes('/payreturn')&&returnUrl.includes('/info')){//原生回调页面
									url=`/pages/packages/info/payreturn/payreturn?ordernum=${returnUrl.match(/ordernum=([^&]*)&/)[1]}`;
								}
								uni.redirectTo({
									url: url || `/pages/redirect/index?url=${options.returnUrl || options.orderurl}`
								});
							}, 2000)
						},
						//小程序支付失败的回调通知
						fail: function(res) {
							uni.showToast({
								title: '支付失败！',
								icon: 'none',
								duration: 2000
							});
							setTimeout(res => {
								var pages = getCurrentPages(); //页面指针数组
								var prepage = pages[pages.length - 2]; //上一页面指针
								//如果没有上一页，跳到指定页面
								//用于像买单页页通过扫码直接进入，放弃支付后的操作
								if (prepage == 'undefined') {
									uni.redirectTo({
										url: '/pages/redirect/index?url=' + encodeURIComponent(options.returnUrl)
									});
								} else {
									app.backFn('/pages/index/index');
								}
							}, 2000)
						}
					});
				
			},

			encode:function (input) {
				var output = "";
				var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
				var i = 0;
				input = _this._utf8_encode(input);
				while (i < input.length) {
					chr1 = input.charCodeAt(i++);
					chr2 = input.charCodeAt(i++);
					chr3 = input.charCodeAt(i++);
					enc1 = chr1 >> 2;
					enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
					enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
					enc4 = chr3 & 63;
					if (isNaN(chr2)) {
						enc3 = enc4 = 64;
					} else if (isNaN(chr3)) {
						enc4 = 64;
					}
					output = output +
					_this._keyStr.charAt(enc1) + _this._keyStr.charAt(enc2) +
					_this._keyStr.charAt(enc3) + _this._keyStr.charAt(enc4);
				}
				return output;
			},
			decode:function (input) {
				var output = "";
				var chr1, chr2, chr3;
				var enc1, enc2, enc3, enc4;
				var i = 0;
				input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
				while (i < input.length) {
					enc1 = _this._keyStr.indexOf(input.charAt(i++));
					enc2 = _this._keyStr.indexOf(input.charAt(i++));
					enc3 = _this._keyStr.indexOf(input.charAt(i++));
					enc4 = _this._keyStr.indexOf(input.charAt(i++));
					chr1 = (enc1 << 2) | (enc2 >> 4);
					chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
					chr3 = ((enc3 & 3) << 6) | enc4;
					output = output + String.fromCharCode(chr1);
					if (enc3 != 64) {
						output = output + String.fromCharCode(chr2);
					}
					if (enc4 != 64) {
						output = output + String.fromCharCode(chr3);
					}
				}
				output = _this._utf8_decode(output);
				return output;
			},
			_utf8_encode:function (string) {
				string = string.replace(/\r\n/g,"\n");
				var utftext = "";
				for (var n = 0; n < string.length; n++) {
					var c = string.charCodeAt(n);
					if (c < 128) {
						utftext += String.fromCharCode(c);
					} else if((c > 127) && (c < 2048)) {
						utftext += String.fromCharCode((c >> 6) | 192);
						utftext += String.fromCharCode((c & 63) | 128);
					} else {
						utftext += String.fromCharCode((c >> 12) | 224);
						utftext += String.fromCharCode(((c >> 6) & 63) | 128);
						utftext += String.fromCharCode((c & 63) | 128);
					}
		
				}
				return utftext;
			},
			_utf8_decode:function (utftext) {
				var string = "";
				var i = 0;
				var c = 0, c1 = 0 ,c2 = 0;
				while ( i < utftext.length ) {
					c = utftext.charCodeAt(i);
					if (c < 128) {
						string += String.fromCharCode(c);
						i++;
					} else if((c > 191) && (c < 224)) {
						c2 = utftext.charCodeAt(i+1);
						string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
						i += 2;
					} else {
						c2 = utftext.charCodeAt(i+1);
						c3 = utftext.charCodeAt(i+2);
						string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
						i += 3;
					}
				}
				return string;
			}

		}
	}
</script>

<style>
	@import url("./pay.css");
</style>